$(document).ready(function () {

  // ----------------- 全局数据--------------------
  let pageNum = 1;
  let pageSize = 5;
  let total = 0;
  let tableData = {};


  // -----------------生命周期（立即执行函数） -----------------
  (function created() {
    loadTableData();
    bindEventListener();
  })()


  function loadTableData() {
    showLoading(true);
    const body = {
      name: $('#search-from-name').val() || null,
    };


    pageAgeGroup(body, {pageNum, pageSize}).then(response => {
      tableData = response.data.records
      total = response.data.total
      renderTable();
      renderPagination();
    }).catch(error => {
      console.error(error);
    })
      .finally(() => {
        showLoading(false);
      });
  }

  // 渲染表格
  function renderTable() {
    const $tbody = $('#tbody');
    $tbody.empty();

    if (tableData.length === 0) {
      $tbody.append(`
                <tr>
                    <td colspan="7" class="text-center py-4 text-muted">No matching data found!</td>
                </tr>
            `);
      return;
    }

    tableData.forEach(item => {
      $tbody.append(`
                <tr>
                    <td>${item.id}</td>
                    <td>
                        <div class="d-flex align-items-center">
                           ${item.name}
                        </div>
                    </td>
                     <td>
                        <div class="d-flex align-items-center">
                           ${item.description}
                        </div>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary edit-btn" data-id="${item.id}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger delete-btn" data-id="${item.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `);
    });
  }

  // 渲染分页
  function renderPagination() {
    const $pagination = $('#pagination');
    $pagination.empty();

    // 上一页按钮
    $pagination.append(`
            <li class="page-item ${pageNum === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${pageNum - 1}">
                    <i class="fas fa-angle-left"></i>
                </a>
            </li>
        `);

    // 页码按钮
    const startPage = Math.max(1, pageNum - 2);
    const endPage = Math.min(Math.ceil(total / pageSize), pageNum + 2);

    for (let i = startPage; i <= endPage; i++) {
      $pagination.append(`
                <li class="page-item ${i === pageNum ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
    }

    // 下一页按钮
    $pagination.append(`
            <li class="page-item ${pageNum === Math.ceil(total / pageSize) ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${pageNum + 1}">
                    <i class="fas fa-angle-right"></i>
                </a>
            </li>
        `);
  }


  // 显示/隐藏加载状态
  function showLoading(show) {
    $('#loading-spinner').toggle(show);
    $('.table-responsive').toggle(!show);
  }

  function bindEventListener() {
    // 搜索按钮点击事件
    $('#search-btn').on('click', function () {
      loadTableData();
    });

    // 重置搜索条件
    $('#reset-btn').on('click', function () {
      $('#search-from-name').val('');
      loadTableData();
    });

    // 分页点击事件
    $('#pagination').on('click', '.page-link', function (e) {
      e.preventDefault();
      const page = $(this).data('page');
      if (page >= 1 && page <= Math.ceil(total / pageSize)) {
        pageNum = page
        loadTableData();
      }
    });

    // 添加用户按钮点击事件
    $('#add-btn').on('click', function () {
      $('#modal-form')[0].reset();
      $('#modal-form-id').val('');
      $('#modal-title').text('添加用户');
      $('#modal').modal('show');
    });

    // 编辑按钮点击事件（委托事件处理）
    const $tbody = $('#tbody');
    $tbody.on('click', '.edit-btn', function () {
      const itemId = $(this).data('id');
      const $btn = $(this);

      $btn.html('<span class="spinner-border spinner-border-sm"></span>');
      $btn.prop('disabled', true);

      getAgeGroup(itemId).then(response => {
        const item = response.data;
        $('#modal-form-id').val(item.id);
        $('#modal-form-name').val(item.name);
        $('#modal-form-description').val(item.description);

        $('#modal-title').text('Update');
        $('#modal').modal('show');

        $('').children()
      })
        .catch(error => {
          console.error('获取用户信息失败:', error);
          alert('获取用户信息失败');
        })
        .finally(() => {
          $btn.html('<i class="fas fa-edit"></i>');
          $btn.prop('disabled', false);
        });
    });

    // 删除按钮点击事件（委托事件处理）
    $tbody.on('click', '.delete-btn', function () {
      const id = $(this).data('id');
      const $btn = $(this);

      if (confirm('Are you sure you delete?')) {
        $btn.html('<span class="spinner-border spinner-border-sm"></span>');
        $btn.prop('disabled', true);

        deleteAgeGroup(id).then(response => {
          if (response.code === 200) {
            alert('Success');
            loadTableData();
          } else {
            alert('Fail: ' + (response.message || 'Unknown Error'));
          }

        })
          .catch(error => {
            alert('Fail');
          })
          .finally(() => {
            $btn.html('<i class="fas fa-trash"></i>');
            $btn.prop('disabled', false);
          });
      }
    });

    // 保存用户表单
    $('#save-btn').on('click', function () {
      const $form = $('#modal-form');
      const id = $('#modal-form-id').val();

      if (!$form[0].checkValidity()) {
        $form[0].reportValidity();
        return;
      }

      const body = {
        id: id || null,
        name: $('#modal-form-name').val(),
        description: $('#modal-form-description').val(),
      };

      const $btn = $(this);
      $btn.html('<span class="spinner-border spinner-border-sm"></span> Saving ...');
      $btn.prop('disabled', true);

      const request = id ? updateAgeGroup(body) : addAgeGroup(body);

      request.then(response => {
        if (response.code === 200) {
          alert('Success');
          $('#modal').modal('hide');
          loadTableData();
        } else {
          alert('Fail' + (response.message || 'Unknown Error'));
        }
      })
        .catch(error => {
          alert('保存用户失败');
        })
        .finally(() => {
          $btn.html('Save');
          $btn.prop('disabled', false);
        });
    });
  }


});